package com.chunxuan.langquan.ui.activity.store;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.ProductEntity;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.GlideUtil;
import com.chunxuan.langquan.support.util.Logg;
import com.chunxuan.langquan.ui.activity.store.adapter.BaseAdapter;
import com.chunxuan.langquan.ui.activity.store.adapter.BaseViewHolder;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class ProductListActivity extends Base2Activity {

    LRecyclerView rlv;
    ImageView ivBack;
    Adapter adapter;
    LRecyclerViewAdapter lRecyclerViewAdapter;
    String fid;
    String sid;
    int currentPage = 1;

    public static void actionStart(Context context, String fid, String sid) {
        Intent intent = new Intent(context, ProductListActivity.class);
        intent.putExtra("fid", fid);
        intent.putExtra("sid", sid);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_product_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    public void initView() {
        //TODO 测试数据
//        fid = getIntent().getStringExtra("fid");
        fid = "43";
//        sid = getIntent().getStringExtra("sid");
        rlv = findViewById(R.id.rv_product_list);
        ivBack = findViewById(R.id.iv_product_list_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        rlv.setLayoutManager(layoutManager);
        adapter = new Adapter();
        lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        rlv.setAdapter(lRecyclerViewAdapter);
        rlv.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                requestData(fid, sid, currentPage);
            }
        });
        rlv.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMore(fid, sid, currentPage++);
            }
        });
        currentPage = 1;
        requestData(fid, sid, currentPage);
    }


    public Disposable requestData(String fid, String sid, final int currentPage) {
        return APIRetrofit.getDefault().requestProductList(Global.HEADER, fid, sid, currentPage)
                .compose(RxUtil.<BaseResult2<List<ProductEntity>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ProductEntity>>>() {
                    @Override
                    public void accept(BaseResult2<List<ProductEntity>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            List<ProductEntity> categorys = result2.getData();
                            if (!isDataEmpty(categorys)) {
                                Logg.e("==产品列表==" + categorys.get(0));
                                adapter.setDatas(categorys);
                                rlv.refreshComplete(currentPage);
                                lRecyclerViewAdapter.notifyDataSetChanged();

                            }
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
//                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取产品列表失败");
                    }
                });
    }

    public Disposable loadMore(String fid, String sid, final int currentPage) {
        return APIRetrofit.getDefault().requestProductList(Global.HEADER, fid, sid, currentPage)
                .compose(RxUtil.<BaseResult2<List<ProductEntity>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ProductEntity>>>() {
                    @Override
                    public void accept(BaseResult2<List<ProductEntity>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            List<ProductEntity> categorys = result2.getData();
                            if (!isDataEmpty(categorys)) {
                                Logg.e("==产品列表==" + categorys.get(0));
                                adapter.addItems(categorys);
                                lRecyclerViewAdapter.notifyDataSetChanged();

                            }
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
//                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取产品列表失败");
                    }
                });
    }


    static class Adapter extends BaseAdapter<ProductEntity> {


        @Override
        public void addItem(ProductEntity value) {
            if (value != null) {
                datas.add(value);
            }
        }

        @Override
        public void setDatas(List<ProductEntity> datas) {
            this.datas = datas;
        }

        @NonNull
        @Override
        public BaseViewHolder<ProductEntity> onCreateViewHolder(@NonNull ViewGroup parent,
                                                                int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
            final View view = layoutInflater.inflate(R.layout.item_product_sub_list, parent, false);
            final ViewHolder viewHolder = new ViewHolder(view);
            viewHolder.tvAddCar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    requestAddProduct(getDatas().get(viewHolder.getAdapterPosition() - 1).getProduct_id());
                }
            });
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ProductDetailActivity.actionStart(view.getContext(),
                            getDatas().get(viewHolder.getAdapterPosition() - 1).getProduct_id());
                }
            });
            return viewHolder;
        }

        @SuppressLint("CheckResult")
        public void requestAddProduct(String id) {
            APIRetrofit.getDefault().addProduct(Global.HEADER, id)
                    .compose(RxUtil.<BaseResult2<String>>subIoObMain())
                    .subscribe(new Consumer<BaseResult2<String>>() {
                        @Override
                        public void accept(BaseResult2<String> result2) throws Exception {
                            if (result2.isSuccess()) {
                                ToastUtils.showShort(result2.getMsg());
                            } else {
                                ToastUtils.showShort(result2.getMsg());
                            }
//                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {

                            throwable.printStackTrace();
                            ToastUtils.showShort("添加商品失败");
                        }
                    });
        }
    }

    static class ViewHolder extends BaseViewHolder<ProductEntity> {
        ImageView iv;
        TextView tvTitle;
        TextView tvPrice;
        TextView tvAddCar;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            iv = itemView.findViewById(R.id.iv_product_list_cover);
            tvTitle = itemView.findViewById(R.id.tv_product_list_price);
            tvPrice = itemView.findViewById(R.id.tv_product_list_name);
            tvAddCar = itemView.findViewById(R.id.tv_product_purchase_now);
        }

        @Override
        public void bindViewHolder(ProductEntity value) {
            GlideUtil.loadImg(value.getImage(), iv);
            tvTitle.setText(value.getTitle());
            tvPrice.setText(value.getSales_price());
        }
    }

}